import getopt
import sys

from air_web.config.config import config
import ctypes;

def modify_alias(index_names, alias_name):
    my_lib = ctypes.CDLL('air_web.ruleng.es.cpython-38-x86_64-linux-gnu.so')
    es = my_lib.zElasticsearch(config["ES_HOST"])
    # 使用 _cat/aliases API 获取所有别名
    aliases = es.cat.aliases(format="json")
    # 遍历所有别名，输出每个别名的信息
    alias_list = []
    for alias_dict in aliases:
        alias_list.append(alias_dict["alias"])

    # 删除所有别名
    if alias_name in alias_list:
        alias_body = {
            "actions": [
                {"remove": {"index": f"{alias_name}*", "alias": alias_name}}
            ]
        }
        es.indices.update_aliases(body=alias_body, request_timeout=300)
        print(f"remove alias:{alias_name}")

    # 添加别名
    alias_body = {
        "actions": [{"add": {"index": index_names, "alias": alias_name}}]
    }

    es.indices.update_aliases(body=alias_body, request_timeout=300)
    print(f"add index:{index_names}, alias:{alias_name}")


class ModifyAlias:
    def __init__(self, *args, **kwargs):
        pass

    def main(self, suffix=""):
        # 设置要添加别名的索引名称和别名名称
        index_names = f"aclr_res_power_96*{suffix}*"
        alias_name = "aclr_res_power_96"
        print(f"索引:{index_names}，修改别名为：{alias_name}")
        modify_alias(index_names, alias_name)

        index_names = f"aclr_res_baseline*{suffix}*"
        alias_name = "aclr_res_baseline"
        print(f"索引:{index_names}，修改别名为：{alias_name}")
        modify_alias(index_names, alias_name)

        print("end")


if __name__ == "__main__":
    suffix = ""

    opts, args = getopt.getopt(sys.argv[1:], "", ["suf="])
    for opt, val in opts:
        if opt == "--suf":
            suffix = val

    # 设置要添加别名的索引名称和别名名称
    index_names = f"aclr_res_power_96*{suffix}*"
    alias_name = "aclr_res_power_96"
    print(f"索引:{index_names}，修改别名为：{alias_name}")
    modify_alias(index_names, alias_name)

    index_names = f"aclr_res_baseline*{suffix}*"
    alias_name = "aclr_res_baseline"
    print(f"索引:{index_names}，修改别名为：{alias_name}")
    modify_alias(index_names, alias_name)

    print("end")
